import os
from PIL import Image, ImageDraw, ImageFont
import logging

def create_default_banner():
    """创建默认推荐内容图片"""
    # 确保目录存在
    banners_dir = 'media/banners'
    if not os.path.exists(banners_dir):
        os.makedirs(banners_dir)
    
    # 设置图片路径
    img_path = os.path.join(banners_dir, 'default-banner.jpg')
    
    # 检查文件是否已存在
    if os.path.exists(img_path):
        print(f"默认推荐图片已存在: {img_path}")
        return
    
    # 创建2:1宽高比的图片
    width, height = 1200, 600
    img = Image.new('RGB', (width, height), color=(248, 249, 250))
    
    try:
        draw = ImageDraw.Draw(img)
        
        # 绘制网格背景
        for x in range(0, width, 50):
            draw.line([(x, 0), (x, height)], fill=(230, 230, 230), width=1)
        for y in range(0, height, 50):
            draw.line([(0, y), (width, y)], fill=(230, 230, 230), width=1)
        
        # 添加文字
        try:
            font_path = "arial.ttf"  # Windows系统默认字体
            title_font = ImageFont.truetype(font_path, 60)
            detail_font = ImageFont.truetype(font_path, 30)
        except Exception:
            # 如果无法加载系统字体，使用默认字体
            title_font = ImageFont.load_default()
            detail_font = ImageFont.load_default()
        
        # 添加标题
        title_text = "推荐内容"
        title_bbox = draw.textbbox((0, 0), title_text, font=title_font)
        title_width = title_bbox[2] - title_bbox[0]
        title_height = title_bbox[3] - title_bbox[1]
        title_position = ((width - title_width) // 2, (height - title_height) // 2 - 50)
        draw.text(title_position, title_text, font=title_font, fill=(100, 100, 100))
        
        # 添加尺寸信息
        size_text = f"推荐尺寸: {width}x{height} (2:1)"
        size_bbox = draw.textbbox((0, 0), size_text, font=detail_font)
        size_width = size_bbox[2] - size_bbox[0]
        size_position = ((width - size_width) // 2, title_position[1] + title_height + 30)
        draw.text(size_position, size_text, font=detail_font, fill=(150, 150, 150))
        
        # 添加边框
        draw.rectangle([(10, 10), (width-10, height-10)], outline=(200, 200, 200), width=2)
        
        # 保存图片
        img.save(img_path, 'JPEG', quality=95)
        print(f"成功创建默认推荐图片: {img_path}")
    except Exception as e:
        print(f"创建默认推荐图片时出错: {str(e)}")
    finally:
        img.close()

if __name__ == "__main__":
    create_default_banner() 